package com.cloudinnov.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.springframework.amqp.core.AmqpTemplate;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.logic.impl.GlobalInitLogicImpl;
import com.cloudinnov.model.EmergecyPhone;

/**
 * @remark 在UDP端口监听，接收处理紧急电话状态变更信息
 */
public class EmergecyPhoneServer {
	public static boolean isListen = true;
	private DatagramSocket datagramSocket = null;
	private String ip;
	private int port;
	public static AmqpTemplate callTemplate;

	public EmergecyPhoneServer(AmqpTemplate callTemplate) {
		EmergecyPhoneServer.callTemplate = callTemplate;
	}
	public void startListen(String ip, int port) {
		this.ip = ip;
		this.port = port;
		startListen();
	}
	public void startListen() {
		try {
			SocketAddress local_addr = new InetSocketAddress(ip, port);
			datagramSocket = new DatagramSocket(local_addr);// 绑定接收UDP数据包
			// datagramSocket = new DatagramSocket(port); 接收 广播消息
		} catch (Exception e) {
			isListen = false;
		}
		GlobalInitLogicImpl.EMERGECY_PHONE_START_UP = true;//标识紧急电话UDP启动成功
		DatagramPacket dp = new DatagramPacket(new byte[64], 64);
		while (isListen) {
			try {
				datagramSocket.receive(dp);// 线程堵塞,等待数据包
				// 去除数据包头"@-" 包尾";" 掐头2去尾1，总共去除3
				String data = new String(dp.getData(), 2, dp.getLength() - 3);// 利用getData()方法取出内容
				String[] phone_status = data.split("_");
				EmergecyPhone emergecyPhone = new EmergecyPhone();
				emergecyPhone.setPhoneId(phone_status[0]);
				emergecyPhone.setStatus(Integer.valueOf(phone_status[1]));
				emergecyPhone.setCurrentTime(String.valueOf(System.currentTimeMillis()));
				callTemplate.convertAndSend(JSON.toJSONString(emergecyPhone));
			} catch (IOException e) {
			} catch (Exception e) {
			}
		}
	}
}
/*
 * 分机8010呼叫：@_8010_03; 分机8011通话：@_8011_01; 起始位： @ 分隔符：下划线，“_” 数据位：分机号码+状态 结束位： 分号，“;” 分机数据编号：规则？
 * 位置详细列表：？
 */
